package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.comparator.CompareUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.config.WebSocketServer;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.AlertDataMapper;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.service.IAlertRuleService;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 报警规则Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-01-17
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper,AlertRule> implements IAlertRuleService
{
    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private IAlertDataService alertDataService;
    @Autowired
    private WebSocketServer webSocketServer;
    /**
     * 查询报警规则
     * 
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询报警规则列表
     * 
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule)
    {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule)
    {
        return save(alertRule)?1:0;
    }

    /**
     * 修改报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule)
    {
        return updateById(alertRule)?1:0;
    }

    /**
     * 批量删除报警规则
     * 
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除报警规则信息
     * 
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id)
    {
        return removeById(id)?1:0;
    }

    @Override
    public void AlertRuleDeviceData() {
        //1.查询拿到所有的上报数据
        List<Object> values = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);
        if(CollUtil.isEmpty(values)){
            return;
        }
        //定义一个List<DeviceData>用于拿到数据
        List<DeviceData> deviceDataList = new ArrayList<>();
        values.forEach(value ->{
            //遍历上报数据的总集合--List<List<DeviceData>>
            String jsonStr = JSONUtil.toJsonStr(value);
            List<DeviceData> list = JSONUtil.toList(jsonStr, DeviceData.class);
            deviceDataList.addAll(list);
        });
        if (CollUtil.isEmpty(deviceDataList)){
            return;
        }
        //2.对集合的上报数据进行遍历 进行匹配规则：
        deviceDataList.forEach(deviceData -> {
            //抽成方法--设计方法
            alertRuleMatchData(deviceData);
        });
    }

    //对拿到的每一个数据进行匹配规则
    private void alertRuleMatchData(DeviceData deviceData) {
      //1.拿到所有设备的上报数据---全部设备对应的iotid是-1
        List<AlertRule> alertRules = list(new LambdaQueryWrapper<AlertRule>().eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getIotId, "-1")
                .eq(AlertRule::getStatus, 1));
        //2.拿到对应的设备规则
        List<AlertRule> deviceAlertRules = list(new LambdaQueryWrapper<AlertRule>().eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getIotId, deviceData.getIotId())
                .eq(AlertRule::getStatus, 1));
        //合并两个规则---alertRules
        alertRules.addAll(deviceAlertRules);
        if (CollUtil.isEmpty(alertRules)){
            return;
        }
        //3.遍历每一条规则 与对应的每一个数据进行匹配
        alertRules.forEach(alertRule -> {
            //设计方法
            matchDeviceAndAlertRule(alertRule,deviceData);
        });
    }

    //匹配遍历得到的每一个数据和规则
    private void matchDeviceAndAlertRule(AlertRule alertRule, DeviceData deviceData) {
        //1.判断生效时间--即数据的上报时间是否在生效时间内
        LocalTime time = deviceData.getAlarmTime().toLocalTime();
        //得到开始和结束时间
        String[] split = alertRule.getAlertEffectivePeriod().split("~");
        LocalTime startTime = LocalDateTimeUtil.parse(split[0],"HH:mm:ss").toLocalTime();
        LocalTime endTime = LocalDateTimeUtil.parse(split[1],"HH:mm:ss").toLocalTime();
        //判断是否在生效时间内
        if (time.isBefore(startTime) || time.isAfter(endTime)){
            return;
        }
        //2.判断数据阈值
        Double value = alertRule.getValue();
        String operator = alertRule.getOperator();
        //拿到数据的值
        Double dataValue = Double.valueOf(deviceData.getDataValue());
        //数据值与阈值进行比较---x>y=1 x=y=0 x<y=-1
        int compare = CompareUtil.compare(dataValue, value);
        if (">=".equals(operator) && compare < 0 || "<".equals(operator) && compare >= 0){
            //TODO:删除reids中的报警数
            redisTemplate.delete("alert:Silent:" + deviceData.getIotId() + ":" + deviceData.getFunctionId() + ":" + alertRule.getId());
            return;
        }
        //3.判断沉默周期：
        Integer alertSilentPeriod = alertRule.getAlertSilentPeriod();
        //从reids中取数据---分层：使用设备id 功能id 规则id
        String SilentPeriod = redisTemplate.opsForValue().get("alert:Silent:" + deviceData.getIotId() + ":" + deviceData.getFunctionId() + ":" + alertRule.getId());
        if (ObjectUtil.isNotNull(SilentPeriod)){
            //不为空则说明沉默时间没结束
            return;
        }
        //4.判断持续周期
        //拿到持续周期
        Integer duration = alertRule.getDuration();
        //从reids中取数据---分层：使用设备id 功能id 规则id
        String durationStr = redisTemplate.opsForValue().get("alert:duration:" + deviceData.getIotId() + ":" + deviceData.getFunctionId() + ":" + alertRule.getId());
        //进行判断 如果为空则说明第一次则赋值1，若不为空则先加一 在判断是否等于持续周期 相同则通过 不同则redis中赋值
        int sum = durationStr==null ? 1: Integer.parseInt(durationStr)+1;
        if (!duration.equals(sum)){
            redisTemplate.opsForValue().set("alert:duration:" + deviceData.getIotId() + ":" + deviceData.getFunctionId() + ":" + alertRule.getId(),sum+"");
        }else {
            //删除reids中的报警数
            redisTemplate.delete("alert:duration:" + deviceData.getIotId() + ":" + deviceData.getFunctionId() + ":" + alertRule.getId());
            //添加redis沉默周期
            redisTemplate.opsForValue().set("alert:Silent:" + deviceData.getIotId() + ":" + deviceData.getFunctionId() + ":" + alertRule.getId(),"1111",duration,TimeUnit.MINUTES);
        }
        //5.判断告警数据类型
        //判断是否是老人数据--0是老人 1是设备
        Integer alertDataType = alertRule.getAlertDataType();
        List<Long> userIds = null;
        if (alertDataType == 0){
            //老人异常数据---判断设备类型-0是随身设备 1是固定设备
            if (deviceData.getLocationType()==0){
                //随身设备--查询护理员--
                userIds = deviceDataMapper.selectNursingUserByElderId(deviceData.getIotId());
            }else {
                //固定设备--通过床位查询护理员
                userIds = deviceDataMapper.selectNursingUserByBedId(deviceData.getIotId());
            }
        }else {
            //设备异常数据---查询维修员--直接根据角色名找到对应的用户id
            userIds = deviceDataMapper.selectRepairUser("维修工");
        }
        //统一查询超级管理员--
        List<Long> userIdList = deviceDataMapper.selectRepairUser("超级管理员");
        //合并两个集合
        Collection<Long> longs = CollUtil.addAll(userIds, userIdList);
        //去重：得到最终的用户id集合
        List<Long> userIdsList = CollUtil.distinct(longs);
        //设计方法--批量保存告警数据
        saveAlertData(deviceData,alertRule,userIdsList);
    }

    private void saveAlertData(DeviceData deviceData, AlertRule alertRule, List<Long> userIdsList) {
        //先赋值
        AlertData alertData = new AlertData();
        BeanUtil.copyProperties(alertRule,alertData,"id");
        alertData.setStatus(0);
        alertData.setAccessLocation(deviceData.getAccessLocation());
        alertData.setLocationType(deviceData.getLocationType());
        alertData.setPhysicalLocationType(deviceData.getPhysicalLocationType());
        alertData.setDeviceDescription(deviceData.getDeviceDescription());
        alertData.setDataValue(deviceData.getDataValue());
        alertData.setAlertRuleId(alertRule.getId());
        alertData.setType(alertRule.getAlertDataType());
        String reason = alertData.getFunctionId()+alertRule.getOperator()+alertRule.getValue() +",持续"+alertRule.getDuration()+"分钟，沉默"+alertRule.getAlertSilentPeriod()+"分钟";
        alertData.setAlertReason(reason);
        List<AlertData> alertDataList = new ArrayList<>();
        userIdsList.forEach(userId -> {
            alertData.setUserId(userId);
            alertDataList.add(alertData);
        });
        alertDataService.saveBatch(alertDataList);

        //发送消息给用户--
        AlertNotifyVo alertNotifyVo = new AlertNotifyVo();
        //赋值给前端需要的数据
        BeanUtil.copyProperties(deviceData,alertNotifyVo);
        alertNotifyVo.setAccessLocation(deviceData.getAccessLocation());
        alertNotifyVo.setFunctionName(alertRule.getFunctionName());
        alertNotifyVo.setAlertDataType(alertRule.getAlertDataType());
        alertNotifyVo.setNotifyType(1);
        webSocketServer.sendMessageToConsumer(alertNotifyVo,userIdsList);
    }
}
